package com.study.limiter;

import com.google.common.io.Files;
import com.study.locks.redis.JedisPoolUtil;
import org.springframework.core.io.ClassPathResource;
import redis.clients.jedis.Jedis;

import java.nio.charset.Charset;

/**
 * 分布式限流
 * 令牌取出 ---> 好像和时间窗用法一样一样的。。。
 *
 * @author: chenhs
 * @date: Created in 15:54 2020/2/2
 **/
public class JedisRateLimiter {

    private String luaScript;
    private String key;

    public JedisRateLimiter(String scriptFile, String key) {
        this.key = key;

        try {
            luaScript = Files.asCharSource(new ClassPathResource(scriptFile).getFile(), Charset.forName("UTF-8")).read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public boolean acquire(){
        Jedis jedis = null;
        try {
            jedis = JedisPoolUtil.getJedis();
            return (Long) jedis.eval(luaScript, 1, key) == 1L;
        } finally {
            // 这里用完一定要关闭
            JedisPoolUtil.closeJedis(jedis);
        }
    }


}
